<?php

	/**
	*	Simple captcha class for another-php-library
	*/

	class AplCaptcha{
		private $img;		//Image handle
		private $width;		//Image width
		private $height;	//Image height
		private $spacing;	//space between characters
		private $noise;		//number of lines/circles or whatever we use to make some noise

		private $opCode;
		private $result;

		public function __construct( $width=180, $height=40,$spacing=5,$noiseFactor = 10)
		{
			$this->width = $width;
			$this->height = $height;
			$this->noise = $noiseFactor;
			$this->spacing = $spacing;
			//Create image and set background to RGB(200,200,200);
			$this->img = imagecreate( $this->width, $this->height );
			imagecolorallocate($this->img, 200, 200, 200);
		}
        /**
        *   Get operand either we add or multiply
        */
		private function getOperand()
		{
			return (rand(0,100)%2==0)?'+':'x';
		}
        /**
        *   Generate operation add or multiply 2 numbers
        */
		private function generateOp()
		{
			$op = $this->getOperand();
			$this->result = null;
			$number1 = rand(0,1000);
			$number2 = rand(0,1000);
			if( $op == '+' )
				$this->result = $number1+$number2;
			else
				$this->result = $number1*$number2;
			return $number1.$op.$number2;
		}

		private function addNoise()
		{
			for( $i = 0; $i < $this->noise; $i++ )
			{
				$randomColor    = rand(200,220);
				$shapeColor     = imagecolorallocate( $this->img, $randomColor, $randomColor, $randomColor );
				imageline( 	$this->img,
							rand(0,$this->width),
							rand(0,$this->height),
							rand(0,$this->width),
							rand(0,$this->height),
							$shapeColor
				);

			}
		}

		private function draw( $fontFile=null )
		{
			$this->opCode = $this->generateOp();
			$codeLen = strlen( $this->opCode );

			if( !empty($fontFile) )
			{
				$font = imageloadfont( $fontFile );
			}
			for( $i = 0; $i < $codeLen; $i++)
			{
				//If no font file is specified then
				//Select a random font size ot make things mixed
				if( empty($fontFile) )
					$font 		= rand(4,5);
				//Choose random color for characters
				$randomColor 	= rand(0,180);
				$fontColor		= imagecolorallocate( $this->img, $randomColor, $randomColor, $randomColor );
				//Write our opCode to image
				imagestring( 	$this->img,
								$font,
								$this->spacing+$i*(imagefontwidth($font)+$this->spacing),
								($this->height-imagefontheight($font))/2,
								$this->opCode[ $i ],
								$fontColor
							);
			}

		}

		public function create( $fontFile=null )
		{
			if( !function_exists("imagejpeg"))
				throw new Exception("Make sure GD extension is enabled!!!");
			$this->addNoise();
			$this->draw($fontFile);
			header('Content-Type:image/jpeg');
			imagejpeg( $this->img );
			imagedestroy( $this->img );
			return true;
		}

		public function getResult()
		{
			return $this->result;
		}

	}

?>  